import { useState, useEffect, useContext } from "react";
import { cn } from "@/lib/utils";
import { motion } from "framer-motion";
import { toast } from "sonner";
import api from "@/services/api";
import { AuthContext } from "@/App";
import UserService from "@/services/user";


interface User {
  userId: string;
  userName: string;
  userIcon: string;
  account: string;
  type?: 'OWNER' | 'PARTICIPANT';
}

interface AddUserModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddUsers: (users: User[]) => void;
  isDark: boolean;
  existingUsers: User[];
  teamId: string | null;
}

const iconOptions = [
  "fa-solid fa-user",
  "fa-solid fa-user-shield",
  "fa-solid fa-user-tie",
  "fa-solid fa-user-ninja",
  "fa-solid fa-user-astronaut",
  "fa-solid fa-user-graduate",
  "fa-solid fa-user-md"
];

export default function AddUserModal({
  isOpen,
  onClose,
  onAddUsers,
  isDark,
  existingUsers,
  teamId
}: AddUserModalProps) {
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
  const [selectedRemoveUsers, setSelectedRemoveUsers] = useState<string[]>([]);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newUser, setNewUser] = useState({
    userName: "",
    userIcon: "fa-solid fa-user",
    account: "",
    password: ""
  });
  const [unassociatedUsers, setUnassociatedUsers] = useState<User[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取未关联团队的用户
  useEffect(() => {
    console.log('AddUserModal useEffect triggered', { 
      isOpen, 
      teamId,
      currentTime: new Date().toISOString()
    });
    
    if (!isOpen) {
      console.log('Skipping fetch - modal not open');
      return;
    }
    
    if (!teamId) {
      console.error('Missing teamId when modal is open', {
        currentTeamId: teamId
      });
      return;
    }
    
    // 重置选中用户和错误状态
    setSelectedUsers([]);
    setSelectedRemoveUsers([]);
    setError(null);
    
    const fetchUnassociatedUsers = async () => {
      console.log('Fetching unassociated users for team:', teamId);
      setIsLoading(true);
      try {
        const res = await api({
          url: '/doc/teamuser/pageUnUnionUser',
          method: 'post',
          data: {
            teamId: teamId // 使用props传入的teamId
          }
        });
        console.log('API response:', res);

        if (res.success && res.data?.records) {
          setUnassociatedUsers(res.data.records.map(user => ({
            userId: user.userId,
            userName: user.userName,
            userIcon: user.userIcon || "fa-solid fa-user",
            account: user.account
          })));
        } else {
          const errorMsg = res.message || '获取用户列表失败';
          console.error('API returned error:', errorMsg);
          setError(errorMsg);
          toast.error(errorMsg);
        }
      } catch (err: any) {
        console.error('获取未关联用户失败:', err);
        const errorMsg = err.message || '获取用户列表失败';
        setError(errorMsg);
        toast.error(errorMsg);
      } finally {
        setIsLoading(false);
      }
    };

    fetchUnassociatedUsers();
  }, [isOpen, teamId]);

  const handleSelectUser = (userId: string) => {
    setSelectedUsers(prev => 
      prev.includes(userId) 
        ? prev.filter(id => id !== userId) 
        : [...prev, userId]
    );
  };

  const handleSelectRemoveUser = (userId: string) => {
    setSelectedRemoveUsers(prev => 
      prev.includes(userId) 
        ? prev.filter(id => id !== userId) 
        : [...prev, userId]
    );
  };

  const handleCreateUser = async () => {
    if (!newUser.userName.trim() || !newUser.account.trim() || !newUser.password) {
      toast.error("请填写完整用户信息");
      return;
    }

    if (!teamId) {
      toast.error("缺少团队ID");
      return;
    }

    setIsLoading(true);
    try {
      const res = await UserService.addUser({
        userName: newUser.userName,
        userIcon: newUser.userIcon,
        account: newUser.account,
        password: newUser.password,
        teamId: teamId
      });

      if (res.success) {
        const user = {
          userId: res.data?.userId || Date.now().toString(),
          userName: newUser.userName,
          userIcon: newUser.userIcon,
          account: newUser.account
        };

        onAddUsers([user]);
        setShowCreateForm(false);
        setNewUser({
          userName: "",
          userIcon: "fa-solid fa-user",
          account: "",
          password: ""
        });
        toast.success("用户创建成功");
      } else {
        toast.error(res.message || "创建用户失败");
      }
    } catch (error: any) {
      console.error('创建用户错误:', error);
      toast.error(error.message || '创建用户失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleAddSelected = async () => {
    if (!teamId) {
      toast.error("缺少团队ID");
      return;
    }

    const usersToAdd = unassociatedUsers.filter(user => 
      selectedUsers.includes(user.userId)
    );

    if (usersToAdd.length === 0) {
      toast.error("请至少选择一个用户");
      return;
    }

    setIsLoading(true);
    try {
      const res = await UserService.addTeamUser({
        teamUserList: usersToAdd.map(user => ({
          userId: user.userId,
          teamId: teamId
        }))
      });

      if (res.success) {
        // 通知父组件添加成员
        onAddUsers(usersToAdd);
        setSelectedUsers([]);
        toast.success("成员添加成功");
        
        // 添加成功后重新拉取两边的数据
        try {
          // 重新拉取未关联用户列表
        const updatedUnassociatedUsers = await fetchUnassociatedUsers();
        setUnassociatedUsers(updatedUnassociatedUsers);
          
          // 通知父组件刷新现有成员列表
          onAddUsers([]); // 传递空数组触发父组件刷新
        } catch (error) {
          console.error('刷新数据失败:', error);
        }
      } else {
        toast.error(res.message || "添加成员失败");
      }
    } catch (error: any) {
      console.error('添加成员错误:', error);
      toast.error(error.message || '添加成员失败');
    } finally {
      setIsLoading(false);
    }
  };

  const handleRemoveSelected = async () => {
    if (!teamId) {
      toast.error("缺少团队ID");
      return;
    }

    const usersToRemove = existingUsers.filter(user => 
      selectedRemoveUsers.includes(user.userId)
    );

    if (usersToRemove.length === 0) {
      toast.error("请至少选择一个用户");
      return;
    }

    // 检查是否包含创建者
    const hasOwner = usersToRemove.some(user => user.type === 'OWNER');
    if (hasOwner) {
      toast.error("创建者不能被移除");
      return;
    }

    setIsLoading(true);
    try {
      const res = await UserService.deleteTeamUser({
        teamUserList: usersToRemove.map(user => ({
          userId: user.userId,
          teamId: teamId
        }))
      });

      if (res.success) {
        // 通知父组件移除成员
        onAddUsers([]); // 传递空数组表示移除操作
        setSelectedRemoveUsers([]);
        toast.success("成员移除成功");
        
        // 移除成功后重新拉取两边的数据
        try {
          // 重新拉取未关联用户列表
          const updatedUnassociatedUsers = await fetchUnassociatedUsers();
          setUnassociatedUsers(updatedUnassociatedUsers);
          
          // 通知父组件刷新现有成员列表
          onAddUsers([]); // 传递空数组触发父组件刷新
        } catch (error) {
          console.error('刷新数据失败:', error);
        }
      } else {
        toast.error(res.message || "移除成员失败");
      }
    } catch (error: any) {
      console.error('移除成员错误:', error);
      toast.error(error.message || '移除成员失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 提取获取未关联用户逻辑为单独函数
  const fetchUnassociatedUsers = async () => {
    if (!teamId) return [];
    
    try {
      const res = await api({
        url: '/doc/teamuser/pageUnUnionUser',
        method: 'post',
        data: { teamId }
      });

      if (res.success && res.data?.records) {
        return res.data.records.map(user => ({
          userId: user.userId,
          userName: user.userName,
          userIcon: user.userIcon || "fa-solid fa-user",
          account: user.account
        }));
      }
      return [];
    } catch (error) {
      console.error('获取未关联用户失败:', error);
      return [];
    }
  };

  if (!isOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <motion.div
        initial={{ opacity: 0, y: 20, scale: 0.95 }}
        animate={{ opacity: 1, y: 0, scale: 1 }}
        exit={{ opacity: 0, y: 20, scale: 0.95 }}
        className={cn(
          "w-full max-w-4xl p-6 rounded-2xl shadow-2xl border",
          isDark ? "bg-gray-800 border-gray-700" : "bg-white border-gray-200"
        )}
      >
        <div className="flex justify-between items-center mb-4">
          <div>
            <h2 className="font-mono font-bold text-xl">团队成员管理</h2>
            <p className="text-gray-500 text-sm mt-1">添加新成员或移除现有成员</p>
          </div>
          <button
            onClick={onClose}
            className={cn(
              "w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200",
              isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
            )}
          >
            <i className="fa-solid fa-times"></i>
          </button>
        </div>

        <div className="grid grid-cols-2 gap-6">
          {/* 左侧：未关联用户列表 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="font-mono text-base font-semibold">可添加用户</h3>
              <span className={cn(
                "px-2 py-1 rounded-full text-xs font-medium",
                isDark ? "bg-blue-900 text-blue-200" : "bg-blue-100 text-blue-800"
              )}>
                {unassociatedUsers.length}位
              </span>
            </div>
            
            {isLoading ? (
              <div className="flex items-center justify-center p-6">
                <i className="fa-solid fa-spinner fa-spin text-lg mr-2 text-blue-500"></i>
                <span className="text-sm">加载中...</span>
              </div>
            ) : error ? (
              <div className="text-red-500 p-3 text-center rounded-lg bg-red-50 dark:bg-red-900/20">
                <p className="text-sm mb-2">{error}</p>
                <button 
                  onClick={() => window.location.reload()}
                  className="px-2 py-1 rounded-md text-xs bg-red-100 hover:bg-red-200 dark:bg-red-800 dark:hover:bg-red-700"
                >
                  重试
                </button>
              </div>
            ) : unassociatedUsers.length === 0 ? (
              <div className="text-center p-6">
                <i className="fa-solid fa-users text-3xl text-gray-400 mb-2"></i>
                <p className="text-sm text-gray-500">暂无可添加的用户</p>
              </div>
            ) : (
              <div className="grid grid-cols-3 gap-1.5 max-h-64 overflow-y-auto">
                {unassociatedUsers.map(user => (
                  <div 
                    key={user.userId}
                    className={cn(
                      "p-1.5 rounded-md flex items-center space-x-1.5 cursor-pointer transition-all duration-200",
                      isDark 
                        ? selectedUsers.includes(user.userId) 
                          ? "bg-blue-900/50 border border-blue-500" 
                          : "hover:bg-gray-700/50"
                        : selectedUsers.includes(user.userId)
                          ? "bg-blue-100 border border-blue-300"
                          : "hover:bg-gray-50"
                    )}
                    onClick={() => handleSelectUser(user.userId)}
                  >
                    <div className={cn(
                      "w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0",
                      isDark ? "bg-gradient-to-br from-gray-700 to-gray-600" : "bg-gradient-to-br from-gray-100 to-gray-200"
                    )}>
                      {user.userIcon.startsWith('http') ? (
                        <img 
                          src={user.userIcon} 
                          alt={user.userName}
                          className="w-full h-full rounded-md object-cover"
                        />
                      ) : (
                        <i className={cn(
                          user.userIcon || "fa-solid fa-user",
                          "text-xs",
                          isDark ? "text-blue-400" : "text-orange-500"
                        )}></i>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-xs truncate">{user.userName}</p>
                      {selectedUsers.includes(user.userId) && (
                        <i className="fa-solid fa-check text-green-500 text-xs"></i>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {unassociatedUsers.length > 0 && selectedUsers.length > 0 && (
              <button
                onClick={handleAddSelected}
                disabled={isLoading}
                className={cn(
                  "w-full py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                  isDark 
                    ? "bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700" 
                    : "bg-gradient-to-r from-blue-500 to-purple-500 hover:from-blue-600 hover:to-purple-600",
                  "text-white shadow-lg hover:shadow-xl text-sm",
                  isLoading ? "opacity-75 cursor-not-allowed" : ""
                )}
              >
                {isLoading ? (
                  <>
                    <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                    添加中...
                  </>
                ) : (
                  <>
                    <i className="fa-solid fa-user-plus mr-2"></i>
                    添加选中用户 ({selectedUsers.length})
                  </>
                )}
              </button>
            )}
          </div>

          {/* 右侧：现有团队成员列表 */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <h3 className="font-mono text-base font-semibold">现有成员</h3>
              <span className={cn(
                "px-2 py-1 rounded-full text-xs font-medium",
                isDark ? "bg-green-900 text-green-200" : "bg-green-100 text-green-800"
              )}>
                {existingUsers.length}位
              </span>
            </div>
            
            {existingUsers.length === 0 ? (
              <div className="text-center p-6">
                <i className="fa-solid fa-user-group text-3xl text-gray-400 mb-2"></i>
                <p className="text-sm text-gray-500">暂无团队成员</p>
              </div>
            ) : (
              <div className="grid grid-cols-3 gap-1.5 max-h-64 overflow-y-auto">
                {existingUsers.map(user => (
                  <div 
                    key={user.userId}
                    className={cn(
                      "p-1.5 rounded-md flex items-center space-x-1.5 transition-all duration-200",
                      user.type === 'OWNER' 
                        ? "opacity-60 cursor-not-allowed" // 创建者不可点击
                        : "cursor-pointer",
                      isDark 
                        ? selectedRemoveUsers.includes(user.userId) 
                          ? "bg-red-900/50 border border-red-500" 
                          : "hover:bg-gray-700/50"
                        : selectedRemoveUsers.includes(user.userId)
                          ? "bg-red-100 border border-red-300"
                          : "hover:bg-gray-50"
                    )}
                    onClick={() => {
                      // 只有非创建者才能被选择移除
                      if (user.type !== 'OWNER') {
                        handleSelectRemoveUser(user.userId);
                      }
                    }}
                  >
                    <div className={cn(
                      "w-6 h-6 rounded-md flex items-center justify-center flex-shrink-0",
                      isDark ? "bg-gradient-to-br from-gray-700 to-gray-600" : "bg-gradient-to-br from-gray-100 to-gray-200"
                    )}>
                      {user.userIcon.startsWith('http') ? (
                        <img 
                          src={user.userIcon} 
                          alt={user.userName}
                          className="w-full h-full rounded-md object-cover"
                        />
                      ) : (
                        <i className={cn(
                          user.type === 'OWNER' ? "fa-solid fa-crown" : (user.userIcon || "fa-solid fa-user"),
                          "text-xs",
                          user.type === 'OWNER' 
                            ? "text-yellow-500" 
                            : (isDark ? "text-blue-400" : "text-orange-500")
                        )}></i>
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium text-xs truncate">{user.userName}</p>
                      <div className="flex items-center space-x-0.5 mt-0.5">
                        {user.type === 'OWNER' && (
                          <span className={cn(
                            "px-0.5 py-0.5 rounded text-xs font-medium",
                            "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300"
                          )}>
                            <i className="fa-solid fa-crown text-xs"></i>
                          </span>
                        )}
                        {user.type === 'PARTICIPANT' && (
                          <span className={cn(
                            "px-0.5 py-0.5 rounded text-xs font-medium",
                            "bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300"
                          )}>
                            <i className="fa-solid fa-user text-xs"></i>
                          </span>
                        )}
                        {selectedRemoveUsers.includes(user.userId) && (
                          <i className="fa-solid fa-times text-red-500 text-xs"></i>
                        )}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {existingUsers.length > 0 && selectedRemoveUsers.length > 0 && (
              <button
                onClick={handleRemoveSelected}
                disabled={isLoading}
                className={cn(
                  "w-full py-2 rounded-lg font-medium transition-all duration-200 transform hover:scale-105",
                  "bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600",
                  "text-white shadow-lg hover:shadow-xl text-sm",
                  isLoading ? "opacity-75 cursor-not-allowed" : ""
                )}
              >
                {isLoading ? (
                  <>
                    <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                    移除中...
                  </>
                ) : (
                  <>
                    <i className="fa-solid fa-user-minus mr-2"></i>
                    移除选中用户 ({selectedRemoveUsers.length})
                  </>
                )}
              </button>
            )}
          </div>
        </div>

        {/* 底部操作区域 */}
        <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
          <div className="text-xs text-gray-500">
            <span>已选择添加: {selectedUsers.length} 位</span>
            <span className="mx-3">|</span>
            <span>已选择移除: {selectedRemoveUsers.length} 位</span>
          </div>
          <div className="flex space-x-2">
            <button
              onClick={() => setShowCreateForm(true)}
              className={cn(
                "px-4 py-2 rounded-lg font-medium transition-all duration-200 text-sm",
                isDark 
                  ? "bg-green-600 hover:bg-green-700" 
                  : "bg-green-500 hover:bg-green-600",
                "text-white"
              )}
            >
              <i className="fa-solid fa-user-plus mr-1"></i>
              新建用户
            </button>
            <button
              onClick={onClose}
              className={cn(
                "px-4 py-2 rounded-lg font-medium transition-all duration-200 text-sm",
                isDark 
                  ? "bg-gray-700 hover:bg-gray-600" 
                  : "bg-gray-200 hover:bg-gray-300"
              )}
            >
              关闭
            </button>
          </div>
        </div>

        {/* 新建用户弹窗 */}
        {showCreateForm && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <motion.div
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              className={cn(
                "w-full max-w-sm p-4 rounded-xl shadow-lg",
                isDark ? "bg-gray-800" : "bg-white"
              )}
            >
              <div className="flex justify-between items-center mb-3">
                <h3 className="font-mono font-bold text-lg">新建用户</h3>
                <button
                  onClick={() => setShowCreateForm(false)}
                  className={cn(
                    "p-1 rounded-full",
                    isDark ? "hover:bg-gray-700" : "hover:bg-gray-100"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>
              <div className="space-y-3">
                <div>
                  <label className="block font-mono text-xs mb-1">用户名</label>
                  <input
                    type="text"
                    value={newUser.userName}
                    onChange={(e) => setNewUser({...newUser, userName: e.target.value})}
                    className={cn(
                      "w-full px-3 py-2 rounded-md border font-mono text-sm",
                      "focus:outline-none focus:ring-2",
                      isDark 
                        ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                        : "border-gray-300 focus:ring-orange-500 bg-white"
                    )}
                    placeholder="输入用户名"
                  />
                </div>
                <div>
                  <label className="block font-mono text-xs mb-1">账号</label>
                  <input
                    type="text"
                    value={newUser.account}
                    onChange={(e) => setNewUser({...newUser, account: e.target.value})}
                    className={cn(
                      "w-full px-3 py-2 rounded-md border font-mono text-sm",
                      "focus:outline-none focus:ring-2",
                      isDark 
                        ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                        : "border-gray-300 focus:ring-orange-500 bg-white"
                    )}
                    placeholder="输入账号"
                  />
                </div>
                <div>
                  <label className="block font-mono text-xs mb-1">密码</label>
                  <input
                    type="password"
                    value={newUser.password}
                    onChange={(e) => setNewUser({...newUser, password: e.target.value})}
                    className={cn(
                      "w-full px-3 py-2 rounded-md border font-mono text-sm",
                      "focus:outline-none focus:ring-2",
                      isDark 
                        ? "border-gray-700 focus:ring-blue-500 bg-gray-700" 
                        : "border-gray-300 focus:ring-orange-500 bg-white"
                    )}
                    placeholder="输入密码"
                  />
                </div>
                <div>
                  <label className="block font-mono text-xs mb-1">用户头像</label>
                  <div className="grid grid-cols-6 gap-1">
                    {iconOptions.map(icon => (
                      <button
                        key={icon}
                        onClick={() => setNewUser({...newUser, userIcon: icon})}
                        className={cn(
                          "p-1.5 rounded-md flex items-center justify-center",
                          newUser.userIcon === icon 
                            ? (isDark ? "bg-blue-600" : "bg-orange-500") 
                            : (isDark ? "hover:bg-gray-700" : "hover:bg-gray-100")
                        )}
                      >
                        <i className={cn(
                          icon,
                          "text-sm",
                          newUser.userIcon === icon ? "text-white" : 
                            (isDark ? "text-blue-400" : "text-orange-500")
                        )}></i>
                      </button>
                    ))}
                  </div>
                </div>
                <div className="flex justify-end space-x-2 pt-2">
                  <button
                    onClick={() => setShowCreateForm(false)}
                    className={cn(
                      "px-3 py-1.5 rounded-md font-medium text-sm",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600" 
                        : "bg-gray-200 hover:bg-gray-300"
                    )}
                  >
                    取消
                  </button>
                  <button
                    onClick={handleCreateUser}
                    className={cn(
                      "px-3 py-1.5 rounded-md font-medium text-sm",
                      isDark 
                        ? "bg-blue-600 hover:bg-blue-700" 
                        : "bg-orange-500 hover:bg-orange-600",
                      "text-white"
                    )}
                  >
                    创建并添加
                  </button>
                </div>
              </div>
            </motion.div>
          </div>
        )}
      </motion.div>
    </div>
  );
}